package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//贴上注解才能扫描
@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

    @Reference
    private IUserInfoCacheService userInfoCacheService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.如果是静态资源,放行
        if ( !(handler instanceof HandlerMethod)) {
            return true;
        }
        //2.如果访问的方法没有贴注解,即无需登录校验,放行
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if ( !handlerMethod.hasMethodAnnotation(RequireLogin.class)) {
            return true;
        }
        //3.从session中获取登录用户信息,如果有,放行,放行
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Consts.USER_INFO);
        if (user != null) {
            return true;
        }
        //4.获取cookie中的token,从redis中查询是否有登录用户,如果有,放行
        Cookie[] cookies = request.getCookies();
        //要对cookies进行判空
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //获取token
                if (cookie.getName().equals(Consts.USER_INFO_TOKEN)) {
                    String token = cookie.getValue();
                    String userInfo = userInfoCacheService.getUserInfo(token);
                    //如果redis中存在登录用户,将其存入session中
                    if (userInfo != null) {
                        session.setAttribute(Consts.USER_INFO, JSON.parseObject(userInfo, UserInfo.class));
                    }
                }
            }
        }



        response.sendRedirect("/login.html");
        return false;
    }
}
